<?php

namespace app\common\model\trends;

use app\common\model\common\UserCensusCount;
use app\common\model\User;
use think\Db;
use think\Model;


class Trends extends Model
{


    // 表名
    protected $name = 'trends';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = false;

    // 定义时间戳字段名
    protected $createTime = false;
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'status_text',
        'user'
    ];


    public function getStatusList()
    {
        return ['0' => __('Status 0'), '1' => __('Status 1'), '2' => __('Status 2')];
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public function getUserAttr($value, $data)
    {
       $nickname = User::where('id',$data['user_id'])->value('nickname');
        return isset($nickname) ? $nickname: '';
    }

    public static function init()
    {
        self::event('after_delete', function ($value) {
            UserCensusCount::where('user_id', $value->user_id)->setDec('user_trends_count');
            UserCensusCount::where('user_id', $value->user_id)->setDec('user_collect_count');            
            Db::name('trends_user_like')->where('trends_id',$value->id)->delete();
        });

        self::event('after_insert', function ($value) {
            UserCensusCount::where('user_id', $value->user_id)->setInc('user_trends_count');
        });
    }


}
